package cn.nbt.busManage.repository;

import cn.nbt.busManage.model.entity.Bus;
import cn.nbt.busManage.model.entity.Driver;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface BusRepository extends CrudRepository<Bus, Integer> {

    /**
     * 更新车辆信息
     * @param bus
     */
    @Modifying
    @Query("update Bus b set b.capacity = :#{#bus.capacity}, " +
            "b.licensePlate = :#{#bus.licensePlate}, " +
            "b.status = :#{#bus.status}, " +
            "b.lastMaintenanceDate = :#{#bus.lastMaintenanceDate}, " +
            "b.nextInspectionDate = :#{#bus.nextInspectionDate} " +
            "where b.id = :#{#bus.id}")
    void updateBus(Bus bus);

    /**
     * 根据id查询司机
     * @param busId 车辆id
     * @return 司机信息
     */
    @Query("FROM Bus b JOIN b.drivers d WHERE b.id = :busId")
    List<Driver> findDriversById(@Param("busId") Integer busId);

    /**
     * 根据车牌号查询车辆
     * @param licensePlate 车牌号
     * @return 车辆信息
     */
    @Query("FROM Bus b WHERE b.licensePlate = :licensePlate")
    Bus findByLicensePlate(@Param("licensePlate") String licensePlate);


    /**
     * 根据线路查询车辆
     * @param id 线路id
     * @return 车辆信息
     */
    @Query("SELECT b FROM Bus b where b.route.id = :id")
    List<Bus> findByRouteId(@Param("id") Integer id);
}
